package kr.co.goodwilldd;

import kr.co.goodwilldd.framework.security.CustomUserDetailService;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/root-context.xml",
		"/appServlet/servlet-context.xml" })
@WebAppConfiguration
public class SuperTestConfiguration {

	@Autowired
	protected WebApplicationContext wac;

	@Autowired
	private FilterChainProxy springSecurityFilterChain;

	@Autowired
	CustomUserDetailService customUserDetailService;
	
	protected String LOGINUSER = "test";

	protected MockMvc mockMvc;

	static {
		System.setProperty("spring.profiles.active", "test");
	}

	@Configuration
	@ComponentScan(basePackageClasses = SuperTestConfiguration.class)
	static class Config {
	}

	@Before
	public void setup() {
		mockMvc = MockMvcBuilders.webAppContextSetup(this.wac)
				.addFilter(springSecurityFilterChain).build();

		SecurityContextHolder.getContext().setAuthentication(
				getPrincipal(LOGINUSER));
	}

	protected UsernamePasswordAuthenticationToken getPrincipal(String username) {
		UserDetails user = customUserDetailService.loadUserByUsername(username);
		UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
				user, user.getPassword(), user.getAuthorities());
		return authentication;
	}
}
